﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using CTEM.Controllers.BUS;
using CTEM.Controllers.Global;
using CTEM.Models;
using CTEM.ModuleForms.EmployeeManagement;
using DevExpress.XtraBars;
using DevExpress.XtraEditors;
using DevExpress.XtraEditors.Controls;
using DevExpress.XtraEditors.DXErrorProvider;
using DevExpress.XtraGrid;
using DevExpress.XtraGrid.Views.Base;
using CTEM.ModuleForms.ManageEmployee;
using DevExpress.Data.Filtering;



namespace CTEM.ModuleForms.EmployeeManagement
{
    public partial class DebtManagement : DevExpress.XtraBars.Ribbon.RibbonForm
    {
        private List<EmployeeAdvanceDTO> _listAdvance;
        private readonly EmployeeBUS _empBus = new EmployeeBUS();
        private readonly string _advanceType;
        private readonly DateTime _fromDate;
        private readonly DateTime _toDate;
        private readonly EmployerDTO _employee;
        private bool _isNew;
        private bool _isEdit;
        private bool _isUpdate;

        public DebtManagement(EmployerDTO employee)
        {
            InitializeComponent();
            _isNew = false;
            _isUpdate = false;
            _employee = employee;
            LoadData();
        }

        public void refreshData(EmployerDTO employee)
        {
            employee.totalDebt = 0;
            List<EmployeeAdvanceDTO> listAdvance = new List<EmployeeAdvanceDTO>();
            listAdvance = _empBus.LoadAdvanceForEmployeeByType("Mượn Tiền Doanh Nghiệp", employee.employeeID);
            foreach (var advance in listAdvance)
            {
                employee.totalDebt += advance.TotalAdvance;
            }
            listAdvance = _empBus.LoadAdvanceForEmployeeByType("Trả Nợ Doanh Nghiệp", employee.employeeID);
            foreach (var advance in listAdvance)
            {
                employee.totalDebt -= advance.TotalAdvance;
            }
            _empBus.UpdateEmployee(employee);
        }

        private void LoadData()
        {
            List<EmployeeAdvanceDTO> listAdvance = new List<EmployeeAdvanceDTO>();
            listAdvance = _empBus.LoadAdvanceForEmployeeByType("Mượn Tiền Doanh Nghiệp", _employee.employeeID);
            _listAdvance = listAdvance;
            listAdvance = _empBus.LoadAdvanceForEmployeeByType("Trả Nợ Doanh Nghiệp", _employee.employeeID);
            foreach (var advance in listAdvance)
            {
                _listAdvance.Add(advance);
            }

            debtManagementbindingSource.DataSource = _listAdvance;

        }

        private  bool ValidateTotalcodtAdvance(EmployeeAdvanceDTO employeeAdvance, out string output, out int i)
        {
            i = 0;
            output = "";
            employeeAdvance.EmployeeID = _employee.employeeID;
            if (employeeAdvance.Reason == null) employeeAdvance.Reason = "";
            if (employeeAdvance.Note == null) employeeAdvance.Note = "";
            if (employeeAdvance.Type == null)
            {
                i = 1;
                output = "Bạn Phải Lựa Chọn Loại trả nợ hay mượn tiền.";
                return false;
            }
            if (employeeAdvance.TotalAdvance < 0)
            {
                i = 2;
                output = "Số tiền nhập vào phải lớn hơn 0.";
                return false;
            }

            return true;
        }

        private void gridView1_RowUpdated(object sender, DevExpress.XtraGrid.Views.Base.RowObjectEventArgs e)
        {

        }

        private void btnDeleteItem_ItemClick(object sender, ItemClickEventArgs e)
        {
            int rowIndex = gridView1.FocusedRowHandle;
            var employeeAdvance = gridView1.GetRow(rowIndex) as EmployeeAdvanceDTO;
            if (employeeAdvance != null)
                if (MessageBox.Show(string.Format("Bạn có chắc chắn muốn xóa không?"), "Cảnh báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning) == DialogResult.Yes)
                {
                    bool success = _empBus.DeleteAdvance(employeeAdvance.AdvanceID);
                    if (success)
                    {

                        LoadData();
                    }
                }
        }

        private void AdvanceManagement_FormClosed(object sender, FormClosedEventArgs e)
        {

            refreshData(_employee);


        }

        private void gridView1_InitNewRow(object sender, DevExpress.XtraGrid.Views.Grid.InitNewRowEventArgs e)
        {
            _isNew = true;
            gridView1.SetRowCellValue(e.RowHandle, "EmployeeID", _employee.employeeID);
            gridView1.SetRowCellValue(e.RowHandle, "FullName", _employee.Fullname);

            gridView1.SetRowCellValue(e.RowHandle, "DateAdvance", DateTime.Today);
        }

        private void AdvanceManagement_Load(object sender, EventArgs e)
        {
            LoadData();
            _isEdit = false;
        }

        private void gridView1_CellValueChanged(object sender, DevExpress.XtraGrid.Views.Base.CellValueChangedEventArgs e)
        {
            if (!_isNew)
            {
                var view = sender as ColumnView;
                var i = e.RowHandle;
                var employeeAdvance = gridView1.GetRow(i) as EmployeeAdvanceDTO;
                if (employeeAdvance != null)
                {
                    string message;

                    int pos;

                    if (!ValidateTotalcodtAdvance(employeeAdvance, out message, out pos))
                    {
                        DialogResult result = MessageBox.Show(message + "\nBạn có muốn nhập lại thông tin", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                        view.SetColumnError(view.Columns[pos], message, ErrorType.Warning);
                        if (result == DialogResult.No)
                        {
                            _isUpdate = false;
                            view.ClearColumnErrors();
                            LoadData();
                            return;
                        }
                        else
                        {
                            _isUpdate = true;
                            gridView1.FocusedRowHandle = i;
                            gridView1.FocusedColumn = e.Column;
                            return;
                        }
                    }

                    if (!_empBus.UpdateEmployeeAdvance(employeeAdvance))
                    {
                        //MessageBox.Show("employeeAdvance" + employeeAdvance.AdvanceID + " 1" + employeeAdvance.EmployeeID + " 2" + employeeAdvance.TotalAdvance + "3 " + employeeAdvance.Note + "4 " + employeeAdvance.Reason + "5 " + employeeAdvance.DateAdvance + "6 " + employeeAdvance.Type);
                        MessageBox.Show("bạn hảy xem lại kết nối tới máy chủ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        _isUpdate = false;
                    }
                    else
                    {
                        alertControlMain.Show(this, Constants.CONFIRM, "Bạn Đã chỉnh sửa Thành Công!");
                        _isUpdate = false;
                        LoadData();

                    }
                }
            }
        }


        private void gridView1_ValidateRow(object sender, DevExpress.XtraGrid.Views.Base.ValidateRowEventArgs e)
        {
            if (_isNew)
            {
                var view = sender as ColumnView;
                var employeeAdvance = e.Row as EmployeeAdvanceDTO;

                string message;

                int pos;

                if (!ValidateTotalcodtAdvance(employeeAdvance, out message, out pos))
                {
                    e.Valid = false;
                    if (view != null)
                    {
                        view.ClearColumnErrors();
                        view.SetColumnError(view.Columns[pos], message, ErrorType.Warning);
                    }
                    DialogResult result = MessageBox.Show(message + "\nBạn có muốn nhập lại thông tin", "Thông báo", MessageBoxButtons.YesNo, MessageBoxIcon.Warning);
                    if (result == DialogResult.No)
                    {
                        _isNew = false;
                        e.Valid = true;
                        LoadData();
                    }
                }
                else
                {

                    if (!_empBus.CreateEmployeeAdvance(employeeAdvance))
                    {

                        MessageBox.Show("bạn hảy xem lại kết nối tới máy chủ", "Thông báo", MessageBoxButtons.OK, MessageBoxIcon.Error);
                        _isNew = false;
                    }
                    else
                    {
                        alertControlMain.Show(this, Constants.CONFIRM, "Bạn Đã tạo mới Thành Công!");
                        _isNew = false;
                        LoadData();

                    }
                }
            }
        }

        private void btnEdit_ItemClick(object sender, ItemClickEventArgs e)
        {
            gridView1.OptionsBehavior.ReadOnly = false;
        }

        private void gridView1_FocusedRowChanged(object sender, FocusedRowChangedEventArgs e)
        {

            if (e.FocusedRowHandle == DevExpress.XtraGrid.GridControl.NewItemRowHandle)
            {

                gridView1.OptionsBehavior.ReadOnly = false;

            }
            else
            {
                gridView1.OptionsBehavior.ReadOnly = !_isEdit;
            }
        }
    }
}
